import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'

const baseURL = process.env.VUE_APP_BASE_API
// create an axios instance
const service = axios.create({
  baseURL: baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})


// 在请求拦截器中添加一个标志 (不然登出时还自动刷新token，退不出来)
let shouldRefreshToken = true;

// request interceptor
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    // 根据 URL 判断是否需要添加 token
    if (config.url.startsWith('/my') && token) {
      // 添加 token 到请求头
      config.headers.Authorization = token;
    }
    // do something before request is sent
    if (token && shouldRefreshToken || config.url.indexOf('/api/') === -1) {
      // let each request carry token
      // please modify it according to the actual situation
      config.headers.Authorization = token
    }
    // console.log(config)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.config.url.indexOf('/api/getUserInfo') === -1) {
      // console.log(response, 'responseresponseresponseresponse')
    }
    if (response.status !== 200) {
      Message({
        message: response.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(response.message || 'Error'))
    } else {
      return response.data
    }
  },
  async error => {
    // 续订token
    // const originalRequest = error.config;
    // if (error.response.status === 401 && !originalRequest._retry && shouldRefreshToken) {  //后端返回401code
    //   originalRequest._retry = true;
    //   try {
    //     const refreshToken = store.state.user['refreshToken'];
    //     const { data } = await axios.post('/api/refreshToken', { refreshToken });
    //     store.commit('SET_TOKENS', data);
    //     originalRequest.headers['Authorization'] = `Bearer ${data.accessToken}`;
    //     return axios(originalRequest);
    //   } catch (e) {
    //     console.error(e);
    //   }
    // }else{
    console.log(error.response.data.message, 'request')
    // }

    return Promise.reject(error);
  }
)

export default service
